package uy.com.tsi2G7.superbet.account.dao;

import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.sql.Timestamp;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;
import org.springframework.orm.hibernate3.HibernateTemplate;

import uy.com.tsi2G7.superbet.account.Account;
import uy.com.tsi2G7.superbet.account.AccountMovement;
import uy.com.tsi2G7.superbet.account.MovementType;

public class AccountStoreEJB implements AccountStore {
	private HibernateTemplate hibernateTemplate;
	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void storeAccount(Account account)throws RemoteException, AccountStoreException{
		try{
			hibernateTemplate.merge(account);
		}catch (Throwable ex){
			throw new AccountStoreException();
		}
	}
	
	public Account getAccount(String user)throws RemoteException, AccountNotFoundException{
		try{
			return (Account)hibernateTemplate.get(Account.class,user);		
		}catch(Exception e){
			throw new AccountNotFoundException();
		}
	}

	@Override
	public void addMovement(String userId, BigDecimal amount, MovementType type)
			throws RemoteException, AccountNotFoundException {
		//TODO hacer transaccional
		Account account = getAccount(userId);
		account.setBalance(account.getBalance().add(amount));
		hibernateTemplate.update(account);
		hibernateTemplate.save(new AccountMovement(amount,new Timestamp(System.currentTimeMillis()), type, userId));
	}
}
